// lib/apiClient.ts

type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'

interface RequestOptions {
    method?: HttpMethod
    body?: any
    headers?: Record<string, string>
}

export class ApiClient {
    private baseUrl: string

    constructor(baseUrl = '') {
        this.baseUrl = baseUrl
    }

    async request<T>(
        url: string,
        { method = 'GET', body, headers = {} }: RequestOptions = {}
    ): Promise<T> {
        const config: RequestInit = {
            method,
            headers: {
                'Content-Type': 'application/json',
                ...headers,
            },
        }

        if (body) {
            config.body = JSON.stringify(body)
        }

        const response = await fetch(this.baseUrl + url, config)

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}))
            throw new Error(
                errorData?.error || `HTTP ${response.status} ${response.statusText}`
            )
        }

        return response.json() as Promise<T>
    }

    get<T>(url: string, headers?: RequestOptions['headers']) {
        return this.request<T>(url, { method: 'GET', headers })
    }

    post<T>(url: string, body?: any, headers?: RequestOptions['headers']) {
        return this.request<T>(url, { method: 'POST', body, headers })
    }

    put<T>(url: string, body?: any, headers?: RequestOptions['headers']) {
        return this.request<T>(url, { method: 'PUT', body, headers })
    }

    delete<T>(url: string, headers?: RequestOptions['headers']) {
        return this.request<T>(url, { method: 'DELETE', headers })
    }
}

// 默认导出一个实例
export const apiClient = new ApiClient()
